package com.rxst.msg.utils;


import com.alibaba.fastjson.JSON;
import com.rxst.msg.base.ResponseVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtUtils implements Serializable {

    static final String CLAIM_KEY_USERNAME = "sub";
    static final String CLAIM_KEY_CREATED = "created";

    static final String USER_ID = "userId";
    static final String ORGANIZATION_CODE = "organizationCode";

  //  @Value("${jwt.token.secret}")
    private String secret="o6sJolctyF9H";
  //  @Value("${jwt.token.expiration}")
    private Long expiration=86400L;


    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public Long getExpiration() {
        return expiration;
    }

    public void setExpiration(Long expiration) {
        this.expiration = expiration;
    }

    public Claims getClaimsFromToken(String token) {
        log.info("====" + secret);
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }


    /**
     * 生成token
     *
     * @param userId   用户ID
     * @param username 用户名
     * @return
     */
    public String generateToken(String userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(USER_ID, userId);
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * @param userId           用户ID
     * @param username         用户名
     * @param organizationCode 机构编号
     * @return
     */
    public String generateToken(String userId, String username, String organizationCode) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(USER_ID, userId);
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(ORGANIZATION_CODE, organizationCode);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, this.secret)
                .compact();
    }

    /**
     * 生成token时间 = 当前时间 + expiration（properties中配置的失效时间）
     *
     * @return
     */
    private Date generateExpirationDate() {
        log.info("XXX:" + expiration);
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 根据token获取用户名
     *
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            final Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 根据token获取用户ID
     *
     * @param token
     * @return
     */
    public String getUserIdFromToken(String token) {
        String userId;
        try {
            final Claims claims = getClaimsFromToken(token);
            userId = (String) claims.get(USER_ID);
        } catch (Exception e) {
            userId = null;
        }
        return userId;
    }

    /**
     * 根据token获取用户的机构编号
     *
     * @param token
     * @return
     */
    public String getOrganizationCodeFromToken(String token) {
        String organizationCode;
        try {
            final Claims claims = getClaimsFromToken(token);
            organizationCode = (String) claims.get(ORGANIZATION_CODE);
        } catch (Exception e) {
            organizationCode = null;
        }
        return organizationCode;
    }

    /**
     * 获取设置的token失效时间
     *
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    /**
     * 判断token失效时间是否到了
     *
     * @param token
     * @return
     */
    public Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 检查token是否有效
     *
     * @param token
     * @return
     */
    public Boolean checkToken(String token) {
        Boolean isValid = false;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            isValid = true;
        }
        return isValid;
    }

    public String refreshToken(String token) {
        final Claims claims = this.getClaimsFromToken(token);
        if (claims != null) {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims);
        } else {
            return null;
        }
    }

    public void responseResult(HttpServletResponse response, ResponseVo result) {
        HttpServletResponse httpResponse = response;
        httpResponse.reset();
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        httpResponse.setStatus(200);
        try {
            OutputStream outputStream = httpResponse.getOutputStream();
            outputStream.write(JSON.toJSONString(result).getBytes("utf-8"));
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean isStartWith(String requestUri, String startWith) {
        boolean flag = false;
        for (String s : startWith.split(",")) {
            if (requestUri.startsWith(s)) {
                return true;
            }
        }
        return flag;
    }

}
